import React, { useState, useMemo, useRef, useEffect } from 'react';
import { Badge, Button, Space, List, message } from 'antd';
import Icon from '@ant-design/icons';
import SplitterLayout from 'react-splitter-layout';
import 'react-splitter-layout/lib/index.css';
import classNames from 'classnames';
import { connectMaster, useModel } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import _ from 'lodash';
import RGL, { WidthProvider } from 'react-grid-layout';
import { saveSettings, getSettings } from '@/services/classBoard';
import DynamicComponent from './components/dynamicComponent';
import imgBook1 from './assets/imgBook1.png';
import imgBook2 from './assets/imgBook2.png';
import imgPlant from './assets/imgPlant.png';
import styles from './index.less';
import styles2 from './data-table.less';

const bell = () => (
  <svg width="1em" height="1em" viewBox="0 0 40 40">
    <path
      d="M16.8386695,38.8990606 C14.2883436,38.8990606 12.226898,36.837615 12.226898,34.2872891 L21.450441,34.2872891 C21.450441,36.829467 19.3808474,38.8990606 16.8386695,38.8990606 Z M31.0487922,31.5821511 L2.62854678,31.5821511 C1.41449387,31.5821511 0.428585123,30.5880943 0.428585123,29.3821894 C0.428585123,28.1681365 1.42264187,27.1822278 2.62854678,27.1822278 C2.62854678,27.1822278 3.72852761,26.7911235 3.90778374,23.5971051 L3.90778374,16.0439034 C3.90778374,9.73734663 8.48696319,4.44114264 14.4838957,3.3330138 L14.4838957,2.67302531 C14.4838957,1.37749233 15.5431365,0.318251534 16.8386695,0.318251534 C18.1342025,0.318251534 19.1934433,1.37749233 19.1934433,2.67302531 L19.1934433,3.3330138 C25.1903758,4.44929064 29.7695552,9.73734663 29.7695552,16.0439034 L29.7695552,21.7230637 L29.7695552,21.7149156 L29.7695552,23.572661 C29.9406633,26.7911235 31.0487922,27.1822278 31.0487922,27.1822278 C32.2628451,27.1822278 33.2487538,28.1762845 33.2487538,29.3821894 C33.2487538,30.5880943 32.2628451,31.5821511 31.0487922,31.5821511 L31.0487922,31.5821511 Z"
      id="形状"
      fill="#FFD029"
    />
    <path
      d="M6.80032592,13.3550613 C7.74549463,12.1898965 9.11435966,11.3750959 10.6869248,11.1550997 C11.1921012,10.5114072 11.8032017,9.94919479 12.4957822,9.49290644 C12.8379985,9.26476227 13.0254026,8.86550997 13.0254026,8.45810966 C13.0254026,7.43146089 11.8765337,6.84480445 11.0291411,7.42331288 C8.95954755,8.80847393 7.4440184,10.9188075 6.80032592,13.3550613 L6.80032592,13.3550613 Z"
      id="路径"
      fill="#FFF0CF"
    />
    <path
      d="M7.77808666,16.883148 C7.00402607,16.883148 6.40922163,16.2150115 6.49884969,15.4490989 C6.61292178,14.4631902 6.80032592,13.3550613 6.80032592,13.3550613 C7.74549463,12.1898965 9.11435966,11.3750959 10.6869248,11.1550997 C10.6869248,11.1550997 9.36694785,13.5750575 9.04917561,15.7913152 C8.95954755,16.4187117 8.41363113,16.883148 7.77808666,16.883148 L7.77808666,16.883148 Z"
      id="路径"
      fill="#FFE36E"
    />
  </svg>
);

const colors = {
  blue: '#1890ff',
  purple: '#722ed1',
  cyan: '#13c2c2',
  green: '#52c41a',
  magenta: '#eb2f96',
  pink: '#ffc0cb',
  red: '#f5222d',
  orange: '#fa8c16',
  yellow: '#fadb14',
  volcano: '#fa541c',
  geekblue: '#2f54eb',
  lime: '#a0d911',
  gold: '#faad14',
};
const ReactGridLayout = WidthProvider(RGL);
const components = [
  { name: '班级文化', w: 1, h: 10 },
  { name: '班级文化_中', w: 2, h: 10 },
  { name: '班级考核积分', w: 2, h: 10 },
  { name: '一周班级积分', w: 2, h: 10 },
  { name: '班级课表', w: 3, h: 20 },
  { name: '学生素养榜', w: 2, h: 10 },
  { name: '优秀作品', w: 2, h: 10 },
  { name: '作业展示', w: 2, h: 10 },
  { name: '学生考勤', w: 2, h: 6 },
  { name: '学生考勤_图', w: 2, h: 10 },
  { name: '值日表', w: 2, h: 5 },
  { name: '课外活动', w: 2, h: 5 },
  { name: '校园动态_大', w: 3, h: 20 },
  { name: '校园动态_中', w: 2, h: 13 },
  { name: '校园动态_小', w: 2, h: 10 },
  { name: '班级学生评价统计_大', w: 2, h: 13 },
  { name: '班级学生评价统计_小', w: 2, h: 10 },
  { name: '阅读统计', w: 2, h: 10 },
  { name: '小组积分统计', w: 2, h: 10 },
];

function Index(props) {
  const {
    masterState: { currentUser },
  } = props;
  console.log('子应用接收共享数据中应含有-masterState:currentUser-->', currentUser);
  const [selectedColor, setSelectedColor] = useState('green');
  const [droppingItem, setDroppingItem] = useState();
  const [layouts, setLayouts] = useState([]);

  const generateDOM = () => {
    return layouts
      .map(function (l) {
        var item = components.find((x) => x.name === l.i);
        if (!item) {
          return null;
        }
        return (
          <div key={item.name} style={{ position: 'relative', overflow: 'hidden' }}>
            <DynamicComponent compName={item.name} />
            {/* <div className="mask" /> */}
            <span
              className={classNames('remove', styles.remove)}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                onRemoveItem(item);
              }}
            >
              X
            </span>
          </div>
        );
      })
      .filter((x) => !!x);
  };

  const onRemoveItem = (i) => {
    setLayouts((layout) => _.reject(layout, { i: i.name }));
  };

  const onLayoutChange = (layout) => {
    setLayouts(layout);
  };

  const onSaveLayout = async () => {
    const model = { layouts, color: colors[selectedColor] };
    const hide = message.loading('正在保存...', 0);
    const response = await saveSettings(model);
    hide();
    if (response.status === true) {
      message.success('保存成功');
    } else {
      message.error(response.message);
    }
  };

  const fetchLayout = async () => {
    const hide = message.loading('加载中...', 0);
    const response = await getSettings(currentUser.schoolNo, currentUser.bjNo);
    hide();
    if (response.status === true) {
      const { layouts, color } = response.result;
      const matchedColor = Object.entries(colors).find(([k, v]) => {
        return v === color;
      });
      setSelectedColor(matchedColor?.[0] || 'green');
      setLayouts(layouts);
    }
  };

  return (
    <PageContainer className={classNames('rgl', styles[`rgl-${selectedColor}`])}>
      <SplitterLayout primaryIndex={1} secondaryInitialSize={300} secondaryMinSize={150}>
        <List
          style={{ height: 700, overflowY: 'auto', paddingRight: 10 }}
          dataSource={components}
          renderItem={(item) => {
            const draggable = !_.some(layouts, { i: item.name });
            return (
              <List.Item>
                <List.Item.Meta
                  title={item.name}
                  description={
                    <div
                      style={{
                        position: 'relative',
                        overflow: 'hidden',
                        zoom: 0.5,
                        width: 'fit-content',
                      }}
                    >
                      <DynamicComponent compName={item.name} />
                      <div
                        className="mask"
                        draggable={draggable}
                        style={{ backgroundColor: 'black', opacity: draggable ? 0 : 0.3 }}
                        onDragStart={(e) => {
                          var dropping = JSON.parse(
                            JSON.stringify(item).replace('"name":', '"i":'),
                          );
                          setDroppingItem(dropping);
                          e.dataTransfer.setData('json_text', JSON.stringify(dropping));
                        }}
                      />
                    </div>
                  }
                />
              </List.Item>
            );
          }}
        />
        <div>
          <Space>
            {_.map(Object.keys(colors), function (color) {
              return (
                <div
                  key={color}
                  className={classNames(
                    color === selectedColor ? styles[`block-selected`] : null,
                    styles[`block-${color}`],
                  )}
                  onClick={() => setSelectedColor(color)}
                />
              );
            })}
            <Button type="primary" size="large" onClick={onSaveLayout} style={{ marginLeft: 50 }}>
              保存
            </Button>
          </Space>
          <div className={styles.page}>
            <img className={styles.imgBook1} src={imgBook1} />
            <img className={styles.imgBook2} src={imgBook2} />
            <img className={styles.imgPlant} src={imgPlant} />
            <div className={classNames('header', styles.header)}>
              <a>
                <img
                  src="http://demo-assets.iwisesoft.com/schoolLogo/board_dltqswxx.png"
                  alt="logo"
                />
                <h1>测试小学 · 2020级4班</h1>
              </a>
              <div style={{ flex: 1 }} />
              <Space>
                <div className={classNames('badgeWrapper,', styles.badgeWrapper)}>
                  <span className={classNames(styles.noticeButton)}>
                    <Badge
                      count={0}
                      style={{
                        boxShadow: 'none',
                      }}
                      className={styles.badge}
                    >
                      {<Icon component={bell} />}
                    </Badge>
                  </span>
                  <span className={classNames('anticon', 'badgeTitle', styles.badgeTitle)}>
                    学校公告
                  </span>
                </div>
              </Space>
            </div>
            <ReactGridLayout
              margin={[10, 0]}
              rowHeight={30}
              cols={7}
              autoSize={false}
              droppingItem={droppingItem}
              isResizable={false}
              isBounded={true}
              isDroppable={true}
              preventCollision={true}
              compactType={null}
              allowOverlap={true}
              layout={layouts}
              onLayoutChange={onLayoutChange}
              onDrop={onLayoutChange}
              onDragStop={onLayoutChange}
              transformScale={0.5}
            >
              {generateDOM()}
            </ReactGridLayout>
          </div>
        </div>
      </SplitterLayout>
    </PageContainer>
  );
}
export default connectMaster(Index);
